package cn.tedu.knows.portal.service.impl;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.mapper.QuestionTagMapper;
import cn.tedu.knows.portal.mapper.UserMapper;
import cn.tedu.knows.portal.mapper.UserQuestionMapper;
import cn.tedu.knows.portal.model.*;
import cn.tedu.knows.portal.mapper.QuestionMapper;
import cn.tedu.knows.portal.service.IQuestionService;
import cn.tedu.knows.portal.service.ITagService;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.QuestionVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.rmi.server.ServerCloneException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2022-01-26
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {

    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public PageInfo<Question> getMyQuestions(String username, Integer pageNum, Integer pageSize) {
        User user=userMapper.findUserByUsername(username);
        QueryWrapper<Question> query=new QueryWrapper<>();
        query.eq("user_id",user.getId());
        query.eq("delete_status",0);
        query.orderByDesc("createtime");
        PageHelper.startPage(pageNum,pageSize);
        List<Question> list=questionMapper.selectList(query);
        for(Question question:list){
            List<Tag> tags=tagNamesToTags(question.getTagNames());
            question.setTags(tags);
        }
        return new PageInfo<>(list);
    }


    @Autowired
    private ITagService tagService;
    private List<Tag> tagNamesToTags(String tagNames){
        //Java基础,Java SE,面试题
        String[] names=tagNames.split(",");
        // names:{"Java基础","Java SE","面试题"}
        Map<String,Tag> tagMap=tagService.getTagMap();
        List<Tag> tags=new ArrayList<>();
        for(String name:names){
            Tag t=tagMap.get(name);
            tags.add(t);
        }
        return tags;
    }

    @Autowired
    private QuestionTagMapper questionTagMapper;
    @Autowired
    private UserQuestionMapper userQuestionMapper;
    @Autowired
    private IUserService userService;

    @Override
    @Transactional
    public void saveQuestion(QuestionVO questionVO, String username) {
        // 查用户
        User user=userMapper.findUserByUsername(username);
        // 拼标签
        StringBuilder builder=new StringBuilder();
        for(String tagName:questionVO.getTagNames()){
            builder.append(tagName).append(",");
        }
        String tagNames=builder.deleteCharAt(builder.length()-1).toString();
        // 实例化Question
        Question question=new Question()
                .setTitle(questionVO.getTitle())
                .setContent(questionVO.getContent())
                .setUserNickName(user.getNickname())
                .setUserId(user.getId())
                .setCreatetime(LocalDateTime.now())
                .setStatus(0)
                .setPageViews(0)
                .setPublicStatus(0)
                .setDeleteStatus(0)
                .setTagNames(tagNames);
        // 新增Question
        int num=questionMapper.insert(question);
        if(num!=1){
            throw new ServiceException("数据库异常!");
        }
        // 新增关系
        Map<String,Tag> tagMap=tagService.getTagMap();
        for (String tagName:questionVO.getTagNames()){
            Tag tag=tagMap.get(tagName);
            QuestionTag questionTag=new QuestionTag()
                    .setTagId(tag.getId())
                    .setQuestionId(question.getId());
            num=questionTagMapper.insert(questionTag);
            if(num!=1){
                throw new ServiceException("数据库异常!");
            }

        }
        Map<String,User> teacherMap=userService.getTeacherMap();
        for(String nickname:questionVO.getTeacherNicknames()){
            User teacher=teacherMap.get(nickname);
            UserQuestion userQuestion=new UserQuestion()
                    .setQuestionId(question.getId())
                    .setUserId(teacher.getId())
                    .setCreatetime(LocalDateTime.now());
            num=userQuestionMapper.insert(userQuestion);
            if(num!=1){
                throw new ServiceException("数据库异常!");
            }
        }


    }


}
